<template>
  <div class="browse-products">
    <h3>百亿补贴</h3>

    <!-- 搜索和分类选择 -->
    <div class="search-bar">
      <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索商品"
          @input="changePage(1)"
      />
      <select v-model="selectedCategory" @change="changePage(1)">
        <option value="">所有分类</option>
        <option v-for="category in categories" :key="category.id" :value="category.name">{{ category.name }}</option>
      </select>


      <!-- 排序选择 -->
      <select v-model="sortOrder" @change="changePage(1)">
        <option value="">默认排序</option>
        <option value="salesQuantity-desc">销量从高到低</option>
        <option value="salesQuantity-asc">销量从低到高</option>
        <option value="viewCount-desc">浏览量从高到低</option>
        <option value="viewCount-asc">浏览量从低到高</option>
      </select>

      <!-- 价格区间选择 -->
      <div>
        <label>价格区间：</label>
        <input type="number" v-model.number="priceMin" placeholder="最低价" />
        <input type="number" v-model.number="priceMax" placeholder="最高价" />
      </div>

      <!-- 时间范围选择 -->
      <div>
        <label>时间范围：</label>
        <input type="date" v-model="startDate" />
        <input type="date" v-model="endDate" />
      </div>
    </div>

    <!-- 商品展示区域 -->
    <div class="products-grid">
      <div class="product-card" v-for="product in paginatedProducts" :key="product.goodsId">
        <img :src="`/api/${product.productImage}`" alt="Product Image" loading="lazy" />

        <h5>{{ product.goodsName }}</h5>
        <p>{{ product.description }}</p>
        <span class="price">
          <i>¥</i>
      <span class="price-int">{{ parsePrice(product.price).int }}</span>
      <span class="price-dec">.{{ parsePrice(product.price).dec }}</span>
</span>

        <BaseButton
            variant="primary"
            size="small"
            @click="viewDetails(product.goodsId)"
        >
          查看详情
        </BaseButton>
      </div>
    </div>

    <!-- 分页和选择每页显示条数 -->
    <div class="pagination-container">
      <select v-model="itemsPerPage" @change="changePage(1)">
        <option :value="5">每页 5 条</option>
        <option :value="10">每页 10 条</option>
        <option :value="20">每页 20 条</option>
        <option :value="40">每页 40 条</option>
        <option :value="80">每页 80 条</option>
      </select>
      <Pagination
          :currentPage="currentPage"
          :totalPages="totalPages"
          @page-change="changePage"
      />
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref, watch} from 'vue';
import {useRouter} from 'vue-router';
import axios from '@/axios'; // 引入axios
import BaseButton from '../components/BaseButton.vue';
import Pagination from '../components/Pagination.vue';

const router = useRouter();

// 商品数据
const allProducts = ref([]);
const searchQuery = ref('');
const selectedCategory = ref('');
const categories = ref([
  { id: 1, name: '电子产品', englishName: "Electronics" },
  { id: 2, name: '家用电器' },
  { id: 3, name: '服装鞋帽' },
]);

// 分页相关
const currentPage = ref(1);
// const itemsPerPage = ref(6); // 默认每页显示 6 条
const itemsPerPage = ref(sessionStorage.getItem('itemsPerPage') || 80)
const totalPages = ref(1);
const sortOrder = ref(''); // 默认排序

const priceMin = ref(null); // 最低价格
const priceMax = ref(null); // 最高价格
const startDate = ref(null); // 开始日期
const endDate = ref(null); // 结束日期

const parsePrice = (price) => {
  const [int, dec] = parseFloat(price || 0).toFixed(2).split('.');
  return { int, dec };
};


// 计算过滤后的商品
const filteredProducts = computed(() => {
  let filtered = allProducts.value;

  // 根据搜索关键字过滤
  if (searchQuery.value.trim() !== '') {
    const query = searchQuery.value.trim().toLowerCase();
    filtered = filtered.filter(product =>
        product.goodsName.toLowerCase().includes(query) ||
        product.description.toLowerCase().includes(query) ||
        product.goodsCategory?.toLowerCase().includes(query)

    );
  }

  console.log(selectedCategory.value)
  // 根据分类过滤
  if (selectedCategory.value !== '') {
    filtered = filtered.filter(product => product.goodsCategory === selectedCategory.value);
  }

// 价格区间过滤
  if (priceMin.value || priceMax.value) {
    filtered = filtered.filter(product => {
      const price = parseFloat(product.price || 0);
      return (!priceMin.value || price >= priceMin.value) &&
          (!priceMax.value || price <= priceMax.value);
    });
  }

  // 时间范围过滤
  if (startDate.value && endDate.value) {
    filtered = filtered.filter(product => {
      const date = new Date(product.specificDate); // 转换为 Date 类型
      return date >= new Date(startDate.value) && date <= new Date(endDate.value);
    });
  }

  // 排序逻辑
  if (sortOrder.value) {
    const [key, order] = sortOrder.value.split('-');
    filtered = filtered.slice().sort((a, b) => {
      const aValue = a[key] || 0; // 如果字段为空，视为 0
      const bValue = b[key] || 0;
      return order === 'asc' ? aValue - bValue : bValue - aValue;
    });
  }


  return filtered;
});

// 计算总页数
const updateTotalPages = () => {
  totalPages.value = Math.ceil(filteredProducts.value.length / itemsPerPage.value);
  sessionStorage.setItem('itemsPerPage', itemsPerPage.value)
};

// 计算当前页显示的商品
const paginatedProducts = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value;
  const end = start + itemsPerPage.value;
  return filteredProducts.value.slice(start, end);
});

// 监听过滤后的商品变化，更新总页数
watch(filteredProducts, () => {
  updateTotalPages();
  // 如果当前页超过总页数，则重置到最后一页
  if (currentPage.value > totalPages.value) {
    currentPage.value = totalPages.value || 1;
  }
});

// 初始化总页数
onMounted(async () => {
  try {
    // 从接口获取商品数据
    const response = await axios.get('/product/all');
    if (response.data.code === 0) {
      // 获取商品数据并处理图片路径
      allProducts.value = response.data.data
      updateTotalPages();
    }
  } catch (error) {
    console.error('获取商品数据失败:', error);
  }
});

// 处理页码变化
const changePage = (page) => {
  currentPage.value = page;
  updateTotalPages(); // 每次改变页码后更新总页数
};

// 查看详情
const viewDetails = (id) => {
  router.push({name: 'ProductDetails', params: {id}});
};
</script>

<style scoped>
.browse-products {
  padding: var(--spacing-large);
  background: var(--background-color) linear-gradient(to bottom, transparent, #fff 260px) radial-gradient(20% 150px at 70% 230px, rgba(0, 210, 255, 0.2), transparent) radial-gradient(40% 180px at 80% 50px, rgba(249, 167, 176, 0.3), transparent) radial-gradient(50% 300px at 90% 100px, rgba(212, 230, 241, 0.8), transparent) radial-gradient(20% 150px at 0px 0px, rgba(162, 213, 239, 0.5), transparent) radial-gradient(30% 200px at 100px 50px, rgba(249, 167, 176, 0.5), transparent);
}

.browse-products h3 {
  margin-bottom: var(--spacing-large);
  color: var(--primary-color);
  text-align: center;
  right: calc(-50%);
}

.search-bar {
  margin-bottom: var(--spacing-large);
  display: flex;
  gap: var(--spacing-base);
  justify-content: center;
  margin-bottom: 20px;
}

.search-bar input,
.search-bar select {
  padding: 10px;
  font-size: 14px;
  border-radius: 5px;
  border: 1px solid #ccc;
}

.search-bar select {
  padding: 10px;
  font-size: 14px;
  border-radius: 5px;
  border: 1px solid #ccc;
  background-color: #fff;
}


.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: var(--spacing-large);
}

.product-card {
  text-indent: 4px;
  border: 1px solid #ddd;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  transition: transform 0.3s, box-shadow 0.3s;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-card:hover {
  transform: translateY(-5px) scale(1.04);
  box-shadow: 0 15px 26px 12px rgba(0, 0, 0, 0.15);
}

.product-card img {
  height: 250px;
  object-fit: cover;
  margin-bottom: var(--spacing-small);
}

/* 标题一行显示，溢出部分省略 */
.product-card h5 {
  color: var(--secondary-color);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 描述最多两行显示，溢出部分省略 */
.product-card p {
  font-size: 14px;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制最多两行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}

.price {
  font-size: 18px;
  color: #e74c3c;
  font-weight: bold;
}

.details-button {
  margin-top: var(--spacing-small);
}

.pagination-container {
  display: flex;
  justify-content: center;  /* 左对齐 */
  align-items: center;  /* 垂直居中对齐 */
  gap: 20px;  /* 控制 select 和分页组件之间的间距 */
  margin-top: 20px;  /* 分页组件与商品列表之间的间距 */
}

.pagination-container select {
  padding: 10px;
  font-size: 14px;
  border-radius: 5px;
  border: 1px solid #ccc;
  background-color: #fff;
}


@media (max-width: 768px) {
  .products-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
}


.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.search-bar input,
.search-bar select,
.search-bar button {
  padding: 8px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.search-bar button {
  cursor: pointer;
  background-color: var(--primary-color);
  color: white;
  border: none;
}

.search-bar label {
  font-weight: bold;
  margin-right: 5px;
}


.price {
  font-size: 18px;
  color: #e74c3c;
  font-weight: bold;
  i {
    font-size: 16px;
    font-weight: 700;
    font-family: MicrosoftYahei-regular, Arial, Helvetica, sans-serif;
    font-style: normal;
    margin-right: 2px;
  }
}

.price-int {
  font-size: 24px; /* 整数部分更大 */
}

.price-dec {
  font-size: 16px; /* 小数部分更小 */
}

</style>
